<link rel="import" href="../components/core-ajax/core-ajax.html">
<link rel="import" href="../components/google-map/google-map.html">
<link rel="import" href="../components/geo-location/geo-location.html">

<polymer-element name="challenge-map" attributes="user_position challenge current_checkpoint_index">
  <template>
    <style>
      google-map {
        display: block;
        height: 100%;
      }
    </style>

    <geo-location
        position="{{ user_position }}"
        watchPos
        highAccuracy>
    </geo-location>

    <google-map id="challenge_google_map" latitude="0" longitude="0" fitToMarkers>
      <google-map-marker
          id="user_location_marker"
          icon="http://support.apple.com/library/APPLE/APPLECARE_ALLGEOS/Product_Help/en_US/PUBLIC_USERS/PP185/IL_BlueDot.png"
          latitude="{{ user_position.coords.latitude }}"
          longitude="{{ user_position.coords.longitude }}">
      </google-map-marker>

      <template repeat="{{ checkpoint, index in challenge.checkpoints }}">
        <google-map-marker
            latitude="{{ checkpoint.latitude }}"
            longitude="{{ checkpoint.longitude }}"
            hidden?="{{ index < current_checkpoint_index }}">
          <span>Checkpoint {{ index }}</span>
        </google-map-marker>
      </template>
    </google-map>

  </template>
  <script>
    Polymer('challenge-map', {
      challenge: { checkpoints: [] },
      current_checkpoint_index: 0,
      center_map: false,
      user_position: { coords: { latitude: 0, longitude: 0, accuracy: 0 } },
      clearMarkers: function() {
        this.$.challenge_google_map.clear();
        this.$.user_location_marker.map = this.$.challenge_google_map;
      },
      challengeChanged: function(old_challenge, new_challenge) {
        this.current_checkpoint_index = 0;
        this.clearMarkers();
      },
      user_positionChanged: function(old_pos, new_pos) {
        if (this.center_map) {
          this.center_map = false;
          this.$.challenge_google_map.latitude = new_pos.coords.latitude;
          this.$.challenge_google_map.longitude = new_pos.coords.longitude;
          if (this.$.challenge_google_map.zoom < 16) { this.$.challenge_google_map.zoom = 16; }
        }
      },
      centerOnCurrentPosition: function() {
        this.center_map = true;
      },
    });
  </script>
</polymer-element>
